package com.asiainfo.sc.demo.gateway;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_DECORATION_FILTER_ORDER;

public class ScZuulFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(ScZuulFilter.class);
    /**
     * per：路由之前，如实现认证、记录调试信息等
     * routing：路由时
     * post：路由后，比如添加HTTP Header
     * error：发生错误时调用
     */

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0; //PRE_DECORATION_FILTER_ORDER  - 1;  // run before PreDecoration
    }

    /**
     * 是否要过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    /**
     * 过滤器的具体逻辑。可用很复杂，包括查sql，nosql去判断该请求到底有没有权限访问。
     */
    @Override
    public Object run() {
        logger.warn("这一句是用来测试的：ScZuulFilter is running!" );
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String channelId = request.getParameter("chn_id");
        //身份认证
        //权限管控
        if(channelId == null) {
            ctx.setSendZuulResponse(false); // 过滤该请求，不对其进行路由
            ctx.setResponseStatusCode(404);
            ctx.setResponseBody("chn_id cannot be empty, 你应该在请求参数中加上 ?chn_id=xx");
        }
        logger.warn("这一句是用来测试的：ScZuulFilter is end!" );
        //return null;

//        String ip = IpUtils.getIpAddr(ctx.getRequest());
//        // 在黑名单中禁用
//        if (StringUtils.isNotBlank(ip) && basicConf != null && basicConf.getIpStr().contains(ip)) {
//            ctx.set("isSuccess", false);
//            ctx.setSendZuulResponse(false);
//            ResponseData data = ResponseData.fail("非法请求", ResponseCode.NO_AUTH_CODE.getCode());
//            ctx.setResponseBody(JsonUtils.toJson(data));
//            ctx.getResponse().setContentType("application/json; charset=utf-8");
//            return null;
//        }
        return null;
    }
}
